var moment = require('moment');
var request = require('request');
var md5 	= require('md5');
var db 		= require('../config/mongo_database');
var jwt 	= require('jsonwebtoken');
var secret 	= require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');
let SMS_URL = 'https://sms.yunpian.com/v2/sms/single_send.json';

exports.register = function(req, res) {
	var username = req.body.username || '';
	var smscode  = req.body.smscode  || '';
	var password = req.body.password || '';
	var inviteid = req.body.inviteid || '';
	var passwordConfirmation = req.body.passwordConfirmation || '';
	if (username == '' || password == '' || password != passwordConfirmation) {
		return res.json({status:400, msg:'用户名或密码不为空'});
	}
	if(username==inviteid){
		return res.json({status:503, msg:'不能输入自己的手机号'});
	}
	var user = new db.userModel();
	user.username = username;
	user.password = password;
	user.remoteip = new Array(req.connection.remoteAddress);
	redisClient.get(username, function (err, code) {
		if(err) return res.json({status:503, msg:'请填写自己手机号'});
		if(smscode==code){ 
			user.save(function(err) {
				if (err) {
					console.log(err)
					return res.json({status:500, msg:'账号已存在'});
				}	
				invited(username, inviteid); // 邀请系统
				return res.json({status:200, msg:'注册成功'});
			});

		}else return res.json({status:501, msg:'验证码不对'});
	});
	
}

// 忘记密码
exports.findpwd = function(req, res){
	let username = req.body.username || '';
	let smscode  = req.body.smscode || '';
	let pwd 	 = req.body.pwd || ''
	let confirmpwd = req.body.confirmpwd || ''
	

	redisClient.get(username, function (err, code) {
		if(err) {
			res.json({status: 501, msg: '不是绑定短信手机号'});
		} 
		if(pwd !== confirmpwd) {
			res.json({status: 501, msg: '两次密码不一致'})
		}
		if(smscode==code){ 
			var whereData = {username:username};
			var updateDat = {$set: {password:md5(pwd)}};
			console.log(updateDat)
			db.userModel.update(whereData, updateDat, function(err, uporder){ 
				if(err){ 
					return res.json({status:500, msg:'设置失败'});
				} else {
					return res.json({status:200, msg:'设置成功' });					
				}		
			})
		}else {
			res.json({status: 502, msg: "手机验证码不正确"}); 
		} 
	});
}

exports.pass = function(req, res, next){
	var username = req.body.username || '';
	db.userModel.findOne({username:username}, function (err, user) {
		if(err) return res.json({status:500, msg:'操作失败'});
		if(null!=user){
			db.userModel.update({username:username}, {$set:{userStatus:'2'}}, function(err, pwduser){ // 执行变更
				return res.json({status:200, msg:'操作成功' });
			})
		}else{
			return res.json({status:500, msg:'操作失败'});
		}
	})
}

// 修改密码
exports.updatepwd = function(req, res, next){
	var oldpwd = req.body.oldpwd || '';
	var newpwd = req.body.newpwd || '';
	var confirmpwd = req.body.confirmpwd || '';
	if (oldpwd == '' || newpwd == '' || confirmpwd == '') { 
		return res.json({status: 402, msg:'参数为空'}); 
	}
	if (newpwd != confirmpwd) { 
		return res.json({status: 402, msg:'两次密码不一致'});
	}
	if(userid=='56064f89ade2f21f36b03136'){
		return res.json({status:500, msg:'操作失败'});
	}
	var userid = tokenManager.getUserId(req);
	db.userModel.findOne({_id:userid}, function (err, user) {
		if(err) return res.json({status:500, msg:'操作失败'});
		if(null!=user){
			if(md5(oldpwd) != user.password) {
				return res.json({status: 501, msg: '原始密码错误'})
			} else {
					db.userModel.update({_id:userid}, {$set:{password:md5(newpwd)}}, function(err, pwduser){ // 执行变更
					if(err){
						return res.json({status:502, msg:'更新失败'});
					} else {
						return res.json({status:200, msg:'操作成功' });			
					}
				})			
			}
		}else{
			return res.json({status:501, msg:'操作失败'});
		}	
	})
}

// 后端登入接口
exports.admin = function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';
	if (username == '' || password == '') { 
		return res.json({status:401, msg:'没有权限'});
	}
	if (username != 'root') { 
		return res.json({status:401, msg:'没有权限'});
	}
	db.userModel.findOne({username: username}, function (err, user) {
		if (err) {
			console.log(err);
			return res.json({status:401, msg:'没有权限'});
		}
		if (user == undefined) {
			return res.json({status:401, msg:'没有权限'});
		}
		user.comparePassword(password, function(isMatch) {
			if (!isMatch) {
				console.log("Attempt failed to login with " + user.username);
				return res.json({status:401, msg:'没有权限'});
            }
            var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
            redisClient.set(token, '{is_expired:false}');
            redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
            return res.json({status:200, msg:'ok', token:token});
			// return res.json({token:token});
		});

	});
};

// 用户登入
exports.signin = async function(req, res) {
	var username = req.body.username || '';
	var password = req.body.password || '';

	if (username == '' || password == '') { 
		return res.json({status:401, msg:'用户名或密码为空'});
	}
	if(username == 'root'){
		return res.json({status:401, msg:'没有权限'});
	}

	db.userModel.findOne({username: username}, function (err, user) {
		console.log(user)
		if (err) {
			console.log(err);
			return res.json({status:401, msg:'登录失败'});
		}

		if (user == undefined) {
			return res.json({status:401, msg:'没有此用户'});
		}

		user.comparePassword(password, async function(isMatch) {
			if (!isMatch) {
				console.log("Attempt failed to login with " + user.username);
				return res.json({status:401, msg:'密码错误'});
            }
            var token = jwt.sign(user, secret.secretToken, {expiresIn: tokenManager.TOKEN_EXPIRATION }); //expiresIn: '24h'
            redisClient.set(token, '{is_expired:false}');
			redisClient.expire(token, tokenManager.TOKEN_EXPIRATION);
					
			console.log(user.nowTime)
			// 更新上次登录时间
			await db.userModel.update({username:username},{$set:{lastTime: user.nowTime, nowTime:moment()}})
			return res.json({status:200, msg:'ok', token:token});
		});
	});
};

// 用户登出
exports.logout = function(req, res) {
	if (req.user) {
		tokenManager.expireToken(req.headers);
		delete req.user;	
		return res.json({status:200, msg:'ok'});
	}
	else {
		return res.json({status:401, msg:'没有权限'});
	}
}

exports.me = function(req, res){
	var user = tokenManager.getUser(req)
	db.userModel.findOne({username: user.username}, function (err, user) {
		if (err) {
			return res.json({status:401, msg:'未登录'});
		}
		return res.json({status:200, msg:'ok', user:user});
	});
}


// 好友邀请系统
function invited(username, inviteid){
	var log = new db.logModel();
	log.name="好友注册";
	log.content = username;
	log.msg = username + ';' + inviteid;
	log.save(function(err){});
	db.userModel.findOne({username: inviteid}, function (err, user) {
		console.log(err, user, (user != undefined))
		if (user != null) {
			var invite = new db.inviteModel();
			invite.userid = username;
			invite.inviteid = inviteid;
			invite.type = user.roletype;
			invite.save(function(err){});
		}
	});
}

exports.updateInfo = async function(req, res) {
	var user = tokenManager.getUser(req);
	var username = user.username;
	var whereData = {username:user.username};
	let oldUser = await db.userModel.findOne(whereData)
	var name = req.body.name || oldUser.name ;
	var idcard = req.body.idcard || oldUser.idcard ;
	var weixin = req.body.weixin || oldUser.weixin ;
	var qq = req.body.qq || oldUser.qq;
	var email = req.body.email || oldUser.email;
	var smscode = req.body.smscode || oldUser.smscode;
	var zhifuPay = req.body.zhifuPay || oldUser.zhifuPay;
	var bankcode = req.body.bankcode || oldUser.bankcode;
	var bankcount = req.body.bankcount || oldUser.bankcode;
	// var wAddress = req.body.wAddress || oldUser.wAddress;

    var updateDat = {$set: {name:name, idcard:idcard,
    						weixin:weixin, qq:qq,
    						userStatus:'1',
    						email:email, 
    						bankcode:bankcode, 
    						bankcount:bankcount, 
							zhifuPay:zhifuPay,
							// wAddress: wAddress,
    						updated:new Date()
    					}
    			    }; 
	// redisClient.get(username, function (err, code) {
	// 	if(err) res.sendStatus(501); //不是绑定短信手机号
	// 	if (smscode==code) { 
			db.userModel.update(whereData, updateDat, function(err, user){
				if(err){return res.json({status:500, msg:'保存失败'});}
				return res.json({status:200, msg:'保存成功'});
			})
		// }else res.sendStatus(502); // 手机验证码不对
	// });	
}

// 发送短信验证码
exports.sendRegMS = function(req, res) {

}

exports.queryBlackuser = function(req, res, next) {
	var userid = tokenManager.getUserId(req);
	if(userid!='56064f89ade2f21f36b03136'){
		return res.sendStatus(500); 
	}else{
		db.userModel.find(function (err, users) {
			for(i in users){
				if(users[i]["username"]=="root"){
					users[i]["username"] = "*****";
				}
				users[i]["password"] = "";
				users[i]["zijinPay"] = "";
				users[i]["zhifuPay"] = "";
				users[i]["is_admin"] = "";
			}
			return res.json({status:200, user:users, msg:"订单查询成功"});
		}).sort({ created : -1 });
	}

};